<template>
  <div class="register-container d-flex align-items-center justify-content-center">
    <div class="card p-5 shadow-lg">
      <h3 class="card-title text-center mb-4">创建 SuperDe 账号</h3>
      <form @submit.prevent="handleRegister">

        <!-- 用户名输入框：只能输入 英文字母+数字 -->
        <div class="mb-4 position-relative">
          <label for="username" class="form-label">用户名</label>
          <input
            type="text"
            class="form-control form-control-lg rounded-pill"
            id="username"
            v-model="username"
            required
            placeholder="请输入英文和数字组成的用户名"
          />
        </div>

        <!-- 电子邮件输入框 -->
        <div class="mb-4 position-relative">
          <label for="email" class="form-label">电子邮件</label>
          <input
            type="email"
            class="form-control form-control-lg rounded-pill"
            id="email"
            v-model="email"
            required
            placeholder="请输入您的电子邮件"
          />
        </div>

        <!-- 密码输入框 -->
        <div class="mb-4 position-relative">
          <label for="password" class="form-label">密码</label>
          <input
            :type="showPassword ? 'text' : 'password'"
            class="form-control form-control-lg rounded-pill"
            id="password"
            v-model="password"
            required
            placeholder="请输入您的密码"
          />
          <!-- 密码可视化切换按钮 -->
          <span class="password-toggle" @click="togglePasswordVisibility">
            <i :class="showPassword ? 'bi bi-eye-slash' : 'bi bi-eye'"></i>
          </span>
        </div>

        <!-- 确认密码输入框 -->
        <div class="mb-4 position-relative">
          <label for="confirmPassword" class="form-label">确认密码</label>
          <input
            :type="showConfirmPassword ? 'text' : 'password'"
            class="form-control form-control-lg rounded-pill"
            id="confirmPassword"
            v-model="confirmPassword"
            required
            placeholder="请再次输入您的密码"
          />
          <!-- 确认密码可视化切换按钮 -->
          <span class="password-toggle" @click="toggleConfirmPasswordVisibility">
            <i :class="showConfirmPassword ? 'bi bi-eye-slash' : 'bi bi-eye'"></i>
          </span>
        </div>

        <!-- 验证码输入框 -->
        <div class="mb-4 position-relative">
          <label for="verification_code" class="form-label">验证码</label>
          <input
            type="text"
            class="form-control form-control-lg rounded-pill"
            id="verification_code"
            v-model="verification_code"
            required
            placeholder="请输入邮箱收到的验证码"
          />
        </div>

        <!-- 发送验证码按钮 -->
        <button
          class="btn btn-outline-primary btn-sm mb-3"
          type="button"
          @click="sendVerificationCode"
        >
          <span v-if="countDown > 0">
            请等待 {{ countDown }} 秒后重试
          </span>
          <span v-else>
            发送验证码
          </span>
        </button>

        <!-- 注册按钮 -->
        <button
          type="submit"
          class="btn btn-success btn-lg w-100 rounded-pill"
          :disabled="isRegistering"
        >
          <span v-if="isRegistering">注册中...</span>
          <span v-else>注册</span>
        </button>
      </form>

      <p class="mt-4 text-center">
        已有账号？ <router-link to="/login">登录</router-link>
      </p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'RegisterView',
  data() {
    return {
      username: '',
      email: '',
      password: '',
      confirmPassword: '',
      verification_code: '',
      showPassword: false,
      showConfirmPassword: false,
      isRegistering: false,
      // 验证码发送倒计时
      countDown: 0,
      timer: null,
    };
  },
  beforeUnmount() {
    // 组件销毁前，清除定时器
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  methods: {
    // 密码可见性切换
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
    toggleConfirmPasswordVisibility() {
      this.showConfirmPassword = !this.showConfirmPassword;
    },

    // 发送验证码
    async sendVerificationCode() {
      // 若两次密码不一致，则提示先修改
      if (this.password !== this.confirmPassword) {
        alert('请先确保两次密码一致后再获取验证码。');
        return;
      }

      // 如果正在倒计时，禁止重复发送
      if (this.countDown > 0) {
        return;
      }

      if (!this.email) {
        alert('请先填写电子邮件');
        return;
      }

      try {
        const res = await axios.post('http://localhost:8080/api/send-verification-email/', {
          email: this.email,
        });
        alert(res.data?.detail || '验证码已发送到您的邮箱！');

        // 前端设置 60秒 倒计时
        this.countDown = 60;
        this.timer = setInterval(() => {
          if (this.countDown > 0) {
            this.countDown--;
          } else {
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);

      } catch (error) {
        if (error.response && error.response.data) {
          const data = error.response.data;
          if (data.email) {
            const emailMsg = data.email.join('，');
            alert('发送验证码失败：' + emailMsg);
          } else if (data.detail) {
            alert('发送验证码失败：' + data.detail);
          } else {
            alert('发送验证码失败，后端错误：' + JSON.stringify(data));
          }
        } else {
          alert('发送验证码失败：网络错误或服务器无响应。');
        }
      }
    },

    // 提交注册
    async handleRegister() {
      // 正则匹配：只能包含英文(a-zA-Z)和数字(0-9)
      const usernameRegex = /^[A-Za-z0-9]+$/;
      if (!usernameRegex.test(this.username)) {
        alert('用户名只能包含英文字母和数字！');
        return;
      }

      // 确认两次密码是否一致
      if (this.password !== this.confirmPassword) {
        alert('两次输入的密码不一致！');
        return;
      }

      try {
        this.isRegistering = true;
        // 后端需要 username / email / password / confirm_password / verification_code
        const payload = {
          username: this.username.trim() || this.email.split('@')[0],
          email: this.email,
          password: this.password,
          confirm_password: this.confirmPassword,
          verification_code: this.verification_code,
        };

        const response = await axios.post('http://localhost:8080/api/register/', payload);

        // 若后端没有抛出错误，即表示注册成功
        alert(response.data?.detail || '注册成功！');

        // 可以选择自动登录
        await this.loginAfterRegister();

      } catch (error) {
        // 在这里解析后端错误信息，做更详细提示
        if (error.response && error.response.data) {
          const data = error.response.data;
          
          // 常见 DRF 字段：
          //   "email": ["该邮箱已被注册。"]
          //   "verification_code": ["验证码错误或已过期"]
          //   "password": ["密码太短，需>=8位"]
          //   "detail": "..."
          //   "non_field_errors": ["..."]
          //   ...
          if (data.email) {
            const msg = data.email.join('，');
            if (msg.includes('已被注册') || msg.includes('already')) {
              alert('该邮箱已被使用，请更换邮箱或直接登录。');
            } else {
              alert('邮箱错误：' + msg);
            }
          } else if (data.verification_code) {
            alert('验证码错误或已过期：' + data.verification_code.join('，'));
          } else if (data.password) {
            alert('密码错误：' + data.password.join('，'));
          } else if (data.detail) {
            alert(data.detail);
          } else if (data.non_field_errors) {
            alert('注册失败：' + data.non_field_errors.join('，'));
          } else {
            alert('注册失败：' + JSON.stringify(data));
          }
        } else {
          alert('网络错误或服务器无响应，注册失败。');
        }
      } finally {
        this.isRegistering = false;
      }
    },

    // 注册后自动登录
    async loginAfterRegister() {
      try {
        const loginRes = await axios.post('http://localhost:8080/api/login/', {
          email: this.email,
          password: this.password,
        });
        const { tokens, user } = loginRes.data;

        localStorage.setItem('accessToken', tokens.access);
        localStorage.setItem('refreshToken', tokens.refresh || '');
        localStorage.setItem('user', JSON.stringify(user));
        localStorage.setItem('isAuthenticated', 'true');

        // 跳转到背诵页面
        this.$router.push({ name: 'recite' });
      } catch (error) {
        console.error('自动登录失败：', error);
        alert('自动登录失败，请手动登录。');
      }
    },
  },
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f4f8, #d9e2ec);
}

.card {
  max-width: 500px;
  width: 100%;
  border: none;
  border-radius: 20px;
  background-color: #ffffff;
}

.card-title {
  color: #333333;
  font-weight: 600;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    'Helvetica Neue', Arial, sans-serif;
}

.form-label {
  color: #555555;
  font-weight: 500;
}

.form-control {
  padding-right: 2.5rem; /* 为密码可视化按钮留出空间 */
  font-size: 1rem;
}

.password-toggle {
  position: absolute;
  top: 70%;
  right: 1.5rem;
  transform: translateY(-50%);
  cursor: pointer;
  color: #aaa;
}

.password-toggle:hover {
  color: #4a90e2;
}

.btn-success {
  background-color: #28a745;
  border: none;
  font-weight: 600;
  transition: background-color 0.3s ease;
}

.btn-success:hover {
  background-color: #218838;
}

.btn-outline-primary {
  transition: background-color 0.3s ease, color 0.3s ease;
}

.shadow-lg {
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

/* 响应式调整 */
@media (max-width: 576px) {
  .card {
    padding: 2rem;
  }
}
</style>
